#include "evm_module.h"

static evm_val_t evm_module_gpio_on(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
    if(argc!=3)
        return EVM_VAL_UNDEFINED;

    if(!evm_is_number(v) || !evm_is_number(v+1) || !evm_2_string(v+2))
        return EVM_VAL_UNDEFINED;

    int id = evm_2_integer(v);
    int instance = evm_2_integer(v+1);
    char *event = (char *)evm_2_string(v+2);

    evm_event_msg_t *msg = evm_module_msg_create();

    int str_len = strlen(event);
    msg->event = evm_malloc(str_len + 1);
    memcpy(msg->event, event,str_len);
    msg->event[str_len] = 0;

    msg->id = instance;

    evm_gpio_t *gpio = evm_module_gpio_getInstance();
    if(gpio == NULL)
        return EVM_VAL_UNDEFINED;

    gpio->on(id, msg);
    return EVM_VAL_UNDEFINED;
}

evm_err_t evm_module_gpio(evm_t *e) {
    if(evm_module_gpio_init()!=0)
        return ec_memory;
    evm_gpio_t *gpio = evm_module_gpio_getInstance();
    if(gpio == NULL)
        return ec_err;
    evm_cffi_t funcs[] = {
        {"setup", (intptr_t)gpio->setup, "iiiii"},
        {"write", (intptr_t)gpio->write, "iii"},
        {"read", (intptr_t)gpio->read, "ii"},
        {"toggle", (intptr_t)gpio->toggle, "ii"},
        {"close", (intptr_t)gpio->close, "vi"},
        {NULL, 0, NULL}
    };

    evm_builtin_t builtin[] = {
        {"on", evm_mk_native((intptr_t)evm_module_gpio_on)},
        {NULL, EVM_VAL_UNDEFINED}
    };
    evm_module_effi_create(e, "@native.pin", funcs , builtin);
    return e->err;
}

